/*
 * SDManager.cpp
 *
 *  Created on: 12/04/2013
 *      Author: roger
 */

#include "SDManager.h"

SDManager::SDManager() {
	m_timeZone = 0;
}

void SDManager::setup(uint8_t SDSelect) {
	low = 124;
	high = 146;
	configLoaded=false;
	select = SDSelect;
}
void SDManager::init() {
	if (!SD.begin(select)) {
		Serial.println("Card failed, or not present");
		// don't do anything more:
		return;
	}
	Serial.println("card initialised.");

}
int SDManager::getHigh() {
	if (!configLoaded)
	{
		loadConfiguration();
	}
	return high;
}

int SDManager::getLow() {
	if (!configLoaded)
	{
		loadConfiguration();
	}
	return low;
}
void SDManager::loadConfiguration() {
	configLoaded = true;
	File dataFile = SD.open("hconfig.txt");
	if (dataFile) {
		low = readInt(dataFile);
		high = readInt(dataFile);
		m_timeZone = readInt(dataFile);
		dataFile.close();
	}
	// if the file isn't open, pop up an error:
	else {
		Serial.println("error opening hconfig.txt");
	}
}
int SDManager::readInt(File dataFile)
{
	String v = "";
	char t = dataFile.read();
	while (t != ',' && t != -1)
	{
		v.append(t);
		t = dataFile.read();
	}
	return v.toInt();
}
char *SDManager::timeString(long elapsed)
{
	tmElements_t tm;
	breakTime(elapsed,tm);
	sprintf(dstring, "%02d:%02d:%02d", tm.Hour,tm.Minute,tm.Second);
	return dstring;
}
char *SDManager::dateString()
{
	long adjustedDate = now() + (m_timeZone * SECS_PER_HOUR);
	sprintf(dstring, "%04d-%02d-%02d %02d:%02d:%02d", year(adjustedDate),month(adjustedDate),day(adjustedDate),hour(adjustedDate),minute(adjustedDate),second(adjustedDate));
	return dstring;
}

void SDManager::logEntry(char *message) {
	if (!configLoaded)
	{
		loadConfiguration();
	}
	File dataFile = SD.open("datalog.txt", FILE_WRITE);
	// if the file is available, write to it:
	if (dataFile) {
		dataFile.println(message);
		dataFile.flush();
		dataFile.close();
	}
	// if the file isn't open, pop up an error:
	else {
		Serial.println("error opening datalog.txt");
		Serial.print(message);
		Serial.println();
	}

}
void SDManager::logEntry(int bpm) {
	if (!configLoaded)
	{
		loadConfiguration();
	}
	File dataFile = SD.open("datalog.txt", FILE_WRITE);
	// if the file is available, write to it:
	if (dataFile) {
		dataFile.print(dateString());
		dataFile.print(",");
		dataFile.print(bpm);
		dataFile.println();
		dataFile.flush();
		dataFile.close();
	}
	// if the file isn't open, pop up an error:
	else {
		Serial.println("error opening datalog.txt");
	}
	Serial.print(dateString());
	Serial.print(",");
	Serial.print(bpm);
	Serial.print(",");
	Serial.print(high);
	Serial.print(",");
	Serial.print(low);
	Serial.println();
}

SDManager::~SDManager() {
}

